package com.fy.controller;

import com.fy.common.JwtUtils;
import com.fy.entity.EpcUser;
import com.fy.utils.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class BaseController {

    public String userName;
    public Integer userId;


    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }


    public EpcUser getUserInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token != null && StringUtils.isNotEmpty(token)) {
            EpcUser userInfo = JwtUtils.getUserInfo(token);
            userName = userInfo.getUserName();
            userId = userInfo.getId();
            return userInfo;
        }
        return new EpcUser();
    }

    /**
     * 封装Json返回信息
     *
     * @param success
     *            是否操作成功
     * @param message
     *            返回辅助信息
     * @param entity
     *            返回数据时实体
     */
    public Map<String, Object> getJsonMap(boolean success, String message, Object entity) {
        Map<String, Object> json = new HashMap<String, Object>(4);
        json.put("success", success);
        json.put("message", message);
        json.put("entity", entity);
        return  json;
    }
}
